package cn.com.w.simple.demo.service.impl;

import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 自定义 spring security 加载用户实现类
 *
 * @author zhangxl
 * @since 2022.3.3
 */
@Service
public class CustomUserDetailsServiceImpl implements UserDetailsService {


    private static Map<String, User> map = new HashMap<>();
    {
        User user = new User("admin",
                "$2a$10$4I6wmReBjJmLzKKo/Kz7SuDSNsPu4ncjjcHs9h0y7EmJ3icD2NIGm",
                AuthorityUtils.commaSeparatedStringToAuthorityList("admin,simple"));
        map.put("admin", user);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println(">>>>>>>>>自定义loadUserByUsername");
        // 模拟根据username查询数据库
        if (!Objects.isNull(map.get(username))) {
            return map.get(username);
        } else {
            throw new UsernameNotFoundException("用户不存在");
        }
    }

}
